import React from 'react';
import { Form, Select } from 'antd';
// 适用云区部分
const { Option } = Select;

// 省份和云区数据
const provinceOptions = ['北京', '天津', '河北', '山东', '山西', '内蒙古'];
const cloudZoneData = {
  '北京': ['北京一区', '北京二区', '北京三区'],
  '天津': ['天津一区', '天津二区'],
  '河北': ['河北一区', '河北二区', '河北三区'],
  '山东': ['山东一区', '山东二区'],
  '山西': ['山西一区'],
  '内蒙古': ['内蒙古一区', '内蒙古二区']
};

const CloudZoneSection = ({ province, cloudZones, onProvinceChange, onCloudZonesChange }) => {
  const handleProvinceChange = (value) => {
    onProvinceChange(value);
    // 初始化选中省份的云区
    const initialZones = {};
    value.forEach(p => {
      initialZones[p] = [];
    });
    onCloudZonesChange(initialZones);
  };

  const handleCloudZoneChange = (values) => {
    // 把选中的云区重新分配回对应省份
    const newZones = {};
    province.forEach(p => {
      newZones[p] = values.filter(v => cloudZoneData[p]?.includes(v));
    });
    onCloudZonesChange(newZones);
  };

  return (
    <div className="section">
      <h3 className="section-title">适用云区</h3>
      <Form.Item
        label="省份"
        name="province"
        // rules={[{ required: true, message: '请选择省份' }]}
      >
        <Select
          mode="multiple"
          value={province}
          onChange={handleProvinceChange}
          placeholder="请选择省份"
          style={{ width: '50%' }}
          showSearch
          filterOption={(input, option) =>
            option?.children?.toLowerCase().includes(input.toLowerCase())
          }
        >
          {provinceOptions.map(p => (
            <Option key={p} value={p}>{p}</Option>
          ))}
        </Select>
      </Form.Item>
      <Form.Item
        label="云区"
        name="cloudZones"
        // rules={[{ required: true, message: '请选择云区' }]}
      >
        <Select
          mode="multiple"
          value={Object.values(cloudZones).flat()}
          onChange={handleCloudZoneChange}
          placeholder="请选择云区"
          style={{ width: '50%' }}
          showSearch
          filterOption={(input, option) =>
            option?.children?.toLowerCase().includes(input.toLowerCase())
          }
        >
          {province.flatMap(p =>
            (cloudZoneData[p] || []).map(zone => (
              <Option key={zone} value={zone}>
                {zone}
              </Option>
            ))
          )}
        </Select>
      </Form.Item>
    </div>
  );
};

export default CloudZoneSection;